<template>
  <div class="medicine-search-card">
    <div class="card-header">
      <i class="icon-search"></i>
      <span class="card-title">药品搜索</span>
      <div class="department-filter">
        <select v-model="selectedDepartment" class="department-select" @change="onDepartmentChange">
          <option value="all">全部科室</option>
          <option v-for="dept in departments" :key="dept" :value="dept">{{ dept }}</option>
        </select>
      </div>
    </div>
    <div class="search-content">
      <div class="search-input-wrapper">
        <input
          type="text"
          v-model="medicineSearch"
          :placeholder="searchPlaceholder"
          class="search-input"
          @input="onSearch"
        >
        <i class="icon-filter"></i>
      </div>
      <div class="medicine-tags">
        <div
          v-for="medicine in filteredMedicines"
          :key="medicine.id"
          class="medicine-tag"
          :class="{
            active: selectedMedicines.includes(medicine.id),
            disabled: isSystemStopped
          }"
          @click="onMedicineToggle(medicine)"
        >
          <span class="tag-icon">{{ medicine.icon || '💊' }}</span>
          <span class="tag-name">{{ medicine.displayName }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import request from '@/utils/request'

// 1. 接收父组件参数
const props = defineProps({
  departments: Array,
  selectedMedicines: Array,
  isSystemStopped: Boolean
})
const emit = defineEmits(['medicine-toggle', 'search', 'department-change'])

// 2. 响应式状态
const medicineSearch = ref('')
const selectedDepartment = ref('all')
const allMedicines = ref([]) // 子组件内部管理药品数据

// 3. 动态生成搜索提示词
const searchPlaceholder = computed(() => {
  return selectedDepartment.value === 'all'
    ? '请输入药品名称...'
    : `请输入${selectedDepartment.value}下的药品名称...`
})

// 4. 辅助函数：处理药品数据（重复名称添加ID后缀）
const processMedicineData = (medicines) => {
  if (!medicines || medicines.length === 0) return []
  const nameCount = {}
  medicines.forEach(med => {
    nameCount[med.name] = (nameCount[med.name] || 0) + 1
  })
  return medicines.map(med => ({
    ...med,
    icon: '💊',
    displayName: nameCount[med.name] > 1 && med.id && typeof med.id.slice === 'function'
      ? `${med.name}(${med.id.slice(-4)})`
      : med.name
  }))
}

/**
 * 核心函数：从后端获取药品列表
 * @param {string} dept - 科室名称，'all' 表示全部
 */
const fetchMedicines = async (dept) => {
  try {
    const response = await request({
      url: '/medicine/list',
      method: 'get',
      params: { department: dept }
    })
    allMedicines.value = processMedicineData(response.data)
    return response.data; // 返回数据，便于父组件链式调用
  } catch (error) {
    console.error('获取药品列表失败：', error)
    allMedicines.value = []
    return []; // 出错时也返回空数组
  }
}

/**
 * 科室切换事件
 */
const onDepartmentChange = async () => {
  medicineSearch.value = ''
  await fetchMedicines(selectedDepartment.value)
  emit('department-change', selectedDepartment.value)
}

/**
 * 搜索事件
 */
const onSearch = async () => {
  try {
    // 如果搜索框为空，则重新加载当前科室的药品列表
    if (!medicineSearch.value.trim()) {
      await fetchMedicines(selectedDepartment.value);
      return;
    }

    // 如果搜索框有内容，则调用新的 /search 接口
    const response = await request({
      url: '/medicine/search', // 调用新的搜索接口
      method: 'get',
      params: {
        department: selectedDepartment.value, // 当前选中的科室
        keyword: medicineSearch.value.trim()  // 搜索框中的关键词
      }
    });
    allMedicines.value = processMedicineData(response.data);
    emit('search', medicineSearch.value);
  } catch (error) {
    console.error('搜索药品失败：', error);
  }
};

/**
 * 药品选择/取消事件
 */
const onMedicineToggle = (medicine) => {
  emit('medicine-toggle', medicine)
}

// 监听父组件已选药品变化
watch(() => props.selectedMedicines, () => {}, { deep: true })

// 计算属性：过滤药品
const filteredMedicines = computed(() => {
  let result = [...allMedicines.value]
  // 当选择全部科室且没有搜索关键词时，只显示前10个药品
  if (selectedDepartment.value === 'all' && !medicineSearch.value) {
    result = result.slice(0, 10)
  } else if (medicineSearch.value) {
    const searchTerm = medicineSearch.value.toLowerCase()
    result = result.filter(medicine =>
      medicine.name.toLowerCase().includes(searchTerm)
    )
  }
  return result
})

// 关键：将 fetchMedicines 方法暴露给父组件
defineExpose({
  fetchMedicines
})
</script>

<style scoped>
.medicine-search-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  margin-bottom: 10px;
}
.card-header {
  display: flex;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f2f5;
}
.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin-left: 10px;
}
.card-header i {
  font-size: 20px;
  color: #4a6cf7;
}
.search-content {
  padding: 20px 24px;
}
.search-input-wrapper {
  position: relative;
  margin-bottom: 20px;
}
.search-input {
  width: 100%;
  padding: 14px 50px 14px 20px;
  border: 2px solid #e8eaf0;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s;
  background: #fafbfc;
}
.search-input:focus {
  border-color: #4a6cf7;
  background: white;
  box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
  outline: none;
}
.icon-filter {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #8f9bb3;
  font-size: 18px;
}
.medicine-tags {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}
.medicine-tag {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fc;
  border: 2px solid #e8eaf0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 100px;
  position: relative;
}
.medicine-tag:hover:not(.disabled) {
  border-color: #4a6cf7;
  transform: translateY(-2px);
}
.medicine-tag.active:not(.disabled) {
  background: linear-gradient(135deg, #4a6cf7, #6c8aff);
  border-color: #4a6cf7;
  color: white;
  box-shadow: 0 4px 12px rgba(74, 108, 247, 0.3);
}
.medicine-tag.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.tag-icon {
  font-size: 24px;
  margin-bottom: 6px;
}
.tag-name {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}
/* 科室筛选 */
.department-filter {
  margin-left: auto;
  margin-right: 15px;
}
.department-select {
  padding: 8px 12px;
  border: 2px solid #e8eaf0;
  border-radius: 8px;
  background: #f8f9fc;
  font-size: 14px;
  color: #1a1a1a;
  cursor: pointer;
  transition: all 0.3s;
}
.department-select:focus {
  border-color: #4a6cf7;
  outline: none;
}
/* 图标样式 */
.icon-search::before { content: "🔍"; }
.icon-filter::before { content: "⚙️"; }
</style>